package wl

import (
	"fmt"
	"github.com/astaxie/beego/logs"
	"github.com/syyongx/php2go"
	"log"
	"os"
	"path/filepath"
	"strings"
	"time"
)

type LogInterface interface {
	Write(err interface{})

}
var beeLog *logs.BeeLogger
var runTimePath string= GetCurrentDirectory()+"/wl/runtime/"

func init()  {

	beeLog = logs.NewLogger(10000) // 创建一个日志记录器，参数为缓冲区的大小

	fmt.Println("开启一个")
	// 设置配置文件
	jsonConfig := `{
        "filename" : "`+runTimePath+time.Now().Format("2006-01-02")+`.log", 
        "maxlines" : 1000,       
        "maxsize"  : 10240       
    }`

	beeLog.SetLogger("file", jsonConfig) // 设置日志记录方式：本地文件记录
	beeLog.SetLevel(logs.LevelDebug)     // 设置日志写入缓冲区的等级
	beeLog.EnableFuncCallDepth(true)     // 输出log时能显示输出文件名和行号（非必须）
}

type Log struct {

} 

func (this *Log)Write(a interface{})  {

	beeLog.Alert(a.(string))

	beeLog.Flush() // 将日志从缓冲区读出，写入到文件
	//beeLog.Close()


}
func GetCurrentDirectory() string {
	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		log.Fatal(err)
	}
	return strings.Replace(dir, "\\", "/", -1)
}



func Wl_write()  {
	var fileName=""

	arg_num := len(os.Args)
	fmt.Printf("the num of input is %d\n",arg_num)


	fmt.Printf("they are :\n")
	for i := 0 ; i < arg_num ;i++{
		fmt.Println(os.Args[i])
	}

	fileName=os.Args[1]

	//fileName="E:\\log.txt"
	fmt.Println(fileName)

	isExit,_:=PathExists(fileName)
	fmt.Println(isExit)
	if(isExit==false){
		f,_:=os.Create(fileName)
		defer f.Close()
	}

	tracefile(fileName,php2go.Uniqid("")+"\n\r")
}


func tracefile(fileName string,str_content string)  {
	fd,_:=os.OpenFile(fileName,os.O_RDWR|os.O_CREATE|os.O_APPEND,0644)
	fd_time:=time.Now().Format("2006-01-02 15:04:05");
	fd_content:=strings.Join([]string{"======",fd_time,"=====",str_content,"\n"},"")
	buf:=[]byte(fd_content)
	fd.Write(buf)
	fd.Close()
}


func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}


	return false, err
}
